<script setup>
import { onMounted, onBeforeMount, reactive, ref } from 'vue';
import { showToast, showDialog, showLoadingToast, closeToast } from 'vant';
import {
    getUrlParam,
    webRequestPayment,
    navigateTo,
    silentLogin,
    getAuthUrl,
    checkEnvConfig,
    wxHideOptionMenu
} from '@/utils';
import { PGuide, CreateRemark, CreateAddress } from '../components';
import store from '@/utils/store';
import useThrottle from '@/utils/useThrottle';
import api from '@/api';

import defaultUser from '@/assets/images/default-user.png';
const isDebug = import.meta.env.VITE_ENABLE_ERUDA;
const maxLength = ref(8);

const state = reactive({
    showLoading: true,
    showPopup: false,
    buyRemark: '',
    remark: '',
    userAvatar: defaultUser,
    payMoney: '',
    sellerInfo: null,
    editAuthHeaderNickAble: true,
    expired: false, // 收款码失效
    appId: '', // H5 认证appid
    h5PayMerchantNo: '', // H5 对应商户号
    errorCode: 0, // 错误码场景
    detail: {
        teamId: '',
        turId: '',
        prohibitedPay: false
    },
    showGuide: true,
    isSubmit: false,
    showPicker: false,
    collectMoneyConfig: {
        receiveInfoSwitch: false
    },
    userReceiveAddress: {
        receiveAddressId: '',
        name: '',
        phone: '',
        province: '',
        city: '',
        area: '',
        detail: ''
    }
});
const areaInfo = ref('');
const showAddressPopup = ref(false);
const addressState = reactive({
    name: '',
    phone: '',
    province: '',
    city: '',
    area: '',
    detail: ''
});

onBeforeMount(() => {
    wxHideOptionMenu();
});

onMounted(async () => {
    const jsCode = getUrlParam('code');
    const isWxEnv = checkEnvConfig();

    if (isWxEnv) {
        const appId = await getPayInfo();
        if (!appId) {
            state.showGuide = false;
            return;
        }
        const userInfo = store.get('USERINFO');
        const authType = store.get('LOGIN_SCOPE');
        const storeAppId = store.get('APP_ID');
        // 用户主动在auth页授权登录后返回, 刷新页面时可能storeAppId 与 appId 不相等时重新走静默授权
        if (authType === 'userinfo' && userInfo && storeAppId === appId && appId) {
            state.showGuide = false;
            store.remove('LOGIN_SCOPE');
            getDetailInfo(() => {
                const detail = store.get('DETAIL_INFO');
                if (detail) {
                    console.log(detail, 11111);
                    state.remark = detail.remark;
                    state.payMoney = detail.payMoney;
                    state.userReceiveAddress = detail.userReceiveAddress;
                    store.remove('DETAIL_INFO');
                }
                handleConfirmKey();
            });
            return;
        }
        // 静默授权后回调返回code进行登录
        if (jsCode && storeAppId === appId && appId) {
            if (
                !userInfo ||
                (userInfo &&
                    userInfo.tokenExpiresTime - 24 * 60 * 60 * 1000 <= new Date().getTime())
            ) {
                await silentLogin(jsCode);
            }
            state.showGuide = false;
            getDetailInfo('');
            return;
        } else {
            // 静默授权
            const turId = getUrlParam('turId');
            const appRoute = getUrlParam('appRoute');
            if (!turId) {
                showDialog({
                    title: '收款码异常，缺少必要信息',
                    confirmButtonText: '确定'
                });
                return;
            }
            appId && store.set('APP_ID', appId);
            // 每次静默授权，删除缓存userInfo，确保每次获取的openId为最新
            store.remove('USERINFO');
            const authUrl = getAuthUrl(`?turId=${turId}&appRoute=${appRoute}`);
            store.set('LOGIN_SCOPE', 'silent');
            navigateTo(authUrl, { routerType: 'replace', isBlank: true });
        }
    } else {
        // pc浏览器调试
        if (import.meta.env.VITE_DEBUG) {
            const userInfo = store.get('USERINFO');
            if (userInfo) {
                state.showGuide = false;
                const curAppId = await getPayInfo();
                curAppId && store.set('APP_ID', curAppId);
                getDetailInfo('');
            } else {
                state.showLoading = false;
            }
        } else {
            state.showLoading = false;
        }
    }
});

/**
 * 获取h5支付的appid和商户号
 */
const getPayInfo = async () => {
    const turId = getUrlParam('turId');
    try {
        const res = await api.fetchGet(
            'getOfficialAccountPayInfo',
            { turId },
            { hasErr: true }
        );
        const { code, data, message } = res || {};
        if (code === 0) {
            const { h5PayMerchantNo, appId } = data;
            state.appId = appId;
            state.h5PayMerchantNo = h5PayMerchantNo;
            return appId;
        } else if (code === 2006101 || code === 4009016) {
            // 没有可用通道 2006101
            // MA绑定异常 4009016
            state.appId = '';
            state.errorCode = code;
            state.showLoading = false;
            return '';
        } else if (code === 4008012) {
            // 请通知商家申请微信商户号
            state.errorCode = code;
            state.showLoading = false;
        } else {
            state.showLoading = false;
            showToast(message);
            return '';
        }
    } catch (err) {
        state.showLoading = false;
        console.log(err);
        showToast('获取支付appId失败');
        return '';
    }
};

const getDetailInfo = async (callback) => {
    const teamId = getUrlParam('teamId');
    const turId = getUrlParam('turId');
    const appRoute = getUrlParam('appRoute');
    try {
        const res = await api.fetchGet(
            'getInfoForCollect',
            { teamId, turId, appRoute },
            { hasErr: true }
        );
        const { code, data, message } = res || {};
        if (code === 0) {
            const {
                sellerInfo,
                sellerTeamId,
                editAuthHeaderNickAble,
                expired,
                collectMoneyConfig,
                userReceiveAddress
            } = data;
            const { prohibitedPay, sellerHeader } = sellerInfo;

            state.sellerInfo = sellerInfo;
            state.userAvatar = sellerHeader
                ? `${sellerHeader}?imageMogr2/thumbnail/128x128`
                : defaultUser;
            state.editAuthHeaderNickAble = editAuthHeaderNickAble;
            state.expired = expired;
            state.detail = {
                teamId: sellerTeamId,
                prohibitedPay,
                turId
            };
            state.userReceiveAddress = userReceiveAddress;
            state.collectMoneyConfig = collectMoneyConfig;
            state.showLoading = false;

            if (prohibitedPay) {
                showDialog({
                    title: '商户收款功能已被关闭，无法付款',
                    confirmButtonText: '确定'
                });
            } else {
                typeof callback === 'function' && callback();
            }
        } else {
            showToast(message);
            state.showLoading = false;
        }
    } catch (err) {
        state.showLoading = false;
        console.log(err);
        showToast('获取商家信息失败 ');
    }
};

const handleConfirmKey = useThrottle(() => {
    const { payMoney, detail, remark, userReceiveAddress, collectMoneyConfig } = state;
    const { teamId, turId, prohibitedPay } = detail;

    // 防止多次点击
    if (state.isSubmit) {
        return;
    }
    state.isSubmit = true;

    const { userStatus, openId } = store.get('USERINFO');
    if (userStatus !== 'AUTHED') {
        store.set('DETAIL_INFO', { remark, payMoney, userReceiveAddress });
        navigateTo('/auth');
        state.isSubmit = false;
        return;
    }

    //禁止支付
    if (prohibitedPay) {
        showDialog({
            title: '商户收款功能已被关闭，无法付款',
            confirmButtonText: '确定'
        });
        state.isSubmit = false;
        return;
    }

    if (Number(payMoney) < 0.1) {
        showDialog({
            title: '最低付款0.1元',
            confirmButtonText: '好'
        });
        state.isSubmit = false;
        return;
    }

    if (Number(payMoney) > 100000) {
        showDialog({
            title: '单次付款上限10万元，请减少付款金额后重试',
            confirmButtonText: '好'
        });
        state.isSubmit = false;
        return;
    }

    // 校验地址
    if (
        (!userReceiveAddress || !userReceiveAddress.receiveAddressId) &&
        collectMoneyConfig.receiveInfoSwitch
    ) {
        showToast('请填写收货信息');
        onAddAddress();
        return;
    }

    let receiveAddressId = collectMoneyConfig.receiveInfoSwitch
        ? userReceiveAddress.receiveAddressId
        : '';

    const param = {
        sellerTeamId: teamId,
        turId,
        remark,
        remarkList: [],
        amount: payMoney,
        receiveAddressId,
        openId
    };

    createOrder(param);
}, 3000);

// 创建订单
const createOrder = async (param) => {
    showLoadingToast({
        message: '加载中...',
        forbidClick: true,
        loadingType: 'spinner'
    });
    try {
        const res = await api.fetchPost('createOrder', param, { hasErr: true });
        const { code, message, data } = res;
        if (code === 0) {
            const { orderId } = data;
            requestPayment({
                orderId,
                turId: param.turId,
                h5PayMerchantNo: state.h5PayMerchantNo
            });
        } else if (code === 4008013) {
            // 未升级电签支付拦截
            state.isSubmit = false;
            closeToast();
            showDialog({
                title: message,
                message: '应三方支付机构监管要求，需完成协议签约后方可收款',
                confirmButtonText: '确认'
            });
        } else if (code === 4008011) {
            state.isSubmit = false;
            closeToast();
            // 请通知商家完成商户认证
            showDialog({
                title: message,
                message: '根据国家法规要求，需要完成商户认证后方可收款',
                confirmButtonText: '确认'
            });
        } else if (code === 4000003) {
            // 超出该商户单笔可收款金额上限
            state.isSubmit = false;
            closeToast();
            showDialog({
                title: message,
                confirmButtonText: '确定'
            });
        } else {
            state.isSubmit = false;
            showToast(message);
        }
    } catch (err) {
        state.isSubmit = false;
        console.log(err);
        showToast('创建支付单失败');
    }
};

// 发起支付
const requestPayment = async (param) => {
    const res = await api.fetchPost('orderToPay', param, { hasErr: true });
    const { code, message, data } = res;
    if (code === 0) {
        store.remove('AUTH_TYPE');
        webRequestPayment(data);
        closeToast();
    } else if (code === 2002015 || code === 2002013 || code === 2002011) {
        closeToast();
        // 2002015 你非当前商家客户，无法付款
        // 2002013 商家收款已关闭
        // 2002011 该商家当日收款已达上限
        showDialog({
            title: message,
            confirmButtonText: '确定'
        });
    } else if (code === 2002016) {
        // 收款码已失效
        state.showGuide = false;
        state.expired = true;
    } else {
        showToast(message);
    }
    state.isSubmit = false;
};

const onClickCloseIcon = () => {
    state.showPopup = false;
    state.buyRemark = state.remark;
};

/**
 * 显示添加地址
 */
const onAddAddress = () => {
    showAddressPopup.value = true;
    const { name, phone, province, city, area, detail } = state.userReceiveAddress;
    areaInfo.value = `${province}${city}${area}`;
    Object.assign(addressState, {
        name,
        phone,
        detail,
        province,
        city,
        area
    });
};

/**
 * 关闭地址
 */
const onAddressClickCloseIcon = () => {
    showAddressPopup.value = false;
};

/**
 * 提交地址
 */
const onAddressConfirm = (value) => {
    state.userReceiveAddress = value;
    showAddressPopup.value = false;
};

const onRemarkConfirm = (value) => {
    state.showPopup = false;
    state.remark = value;
};

const onAddRemark = () => {
    state.showPopup = true;
};

const onKeyborderChange = (e) => {
    let payMoney = state.payMoney;
    let value = e.target.innerText || e.srcElement.innerText;
    if (
        /^(([1-9]\d{1,5})|\d)(\.\d{1,2}){0,1}$/.test(value) ||
        (/^\d+$/.test(payMoney) && value === '.')
    ) {
        if (payMoney === '0' && value !== '.') {
            return;
        } else {
            const curIndex = payMoney.indexOf('.');
            if (curIndex !== -1 && payMoney.length > curIndex + 2) {
                value = payMoney.slice(0, curIndex + 3);
            } else {
                value = `${payMoney}${value}`;
            }
            if (value.length > maxLength.value) {
                value = value.slice(0, maxLength.value);
            }
        }
    } else {
        return;
    }
    state.payMoney = value;
    console.log('keyborderInput==', value);
};

const handleDeleteKey = () => {
    let payMoney = state.payMoney;
    const value = payMoney && payMoney.length !== 1 ? payMoney.slice(0, payMoney.length - 1) : '';
    state.payMoney = value;
};

const handleClearStore = () => {
    store.clearAll();
};
</script>

<template>
    <van-button
        size="mini"
        type="warning"
        class="debug-class"
        v-if="isDebug"
        @click="handleClearStore"
        >清除缓存</van-button
    >
    <c-page :loading="state.showLoading">
        <p-guide :show="state.showGuide"></p-guide>
        <!-- 没有获取到appid商户通道 -->
        <c-result
            v-if="!state.showGuide && !state.appId && state.errorCode === 2006101"
            title="未获取到可用通道"
            info-text="请通知商家联系生意云客服"
        ></c-result>
        <c-result
            v-if="!state.showGuide && !state.appId && state.errorCode === 4009016"
            title="MA绑定异常"
            info-text="请通知商家联系生意云客服"
        ></c-result>
        <c-result
            v-if="!state.showGuide && state.errorCode === 4008012"
            icon-name="guard1"
            title="请通知商家申请微信商户号"
            info-text="应监管要求，需申请微信商户号后可收款"
        ></c-result>
        <c-result
            v-if="!state.showGuide && state.expired"
            title="收款码已失效"
            info-text="请通知商家重新保存收款码"
        ></c-result>
        <div class="order-pay" v-if="!state.showGuide && !state.expired && state.errorCode === 0">
            <div class="user-info">
                <img class="header-img" :src="state.userAvatar" />
                <div class="seller-info">
                    <div class="name ellipsis-one">{{
                        state.sellerInfo && state.sellerInfo.sellerName
                    }}</div>
                </div>
            </div>
            <div class="pay-content">
                <div class="input-section">
                    <div class="label">
                        <div class="title">付款金额</div>
                    </div>
                    <div class="input-box">
                        <div class="unit">¥</div>
                        <div class="value">{{ state.payMoney }}</div>
                        <div class="focus"></div>
                    </div>
                </div>
                <div class="content-box">
                    <div class="cell-group">
                        <van-cell
                            class="note-cell"
                            :style="{ borderRadius: state.remark ? '10px 10px 0 0' : '10px' }"
                            icon-prefix="icon"
                            icon="message1"
                            is-link
                            v-if="
                                state.collectMoneyConfig.receiveInfoSwitch &&
                                state.userReceiveAddress.phone
                            "
                            :border="state.remark"
                            @click="onAddAddress"
                        >
                            <template #icon>
                                <c-icon name="location1" color="#555555" />
                            </template>
                            <template #title>
                                <div>
                                    <div
                                        class="title"
                                        v-if="
                                            state.userReceiveAddress.name ||
                                            state.userReceiveAddress.phone
                                        "
                                    >
                                        {{ state.userReceiveAddress.name }}
                                        {{ state.userReceiveAddress.phone }}
                                    </div>
                                    <div v-else class="title">请填写收货信息</div>
                                    <div class="desc" v-if="state.userReceiveAddress.province">
                                        {{ state.userReceiveAddress.province
                                        }}{{ state.userReceiveAddress.city
                                        }}{{ state.userReceiveAddress.area
                                        }}{{ state.userReceiveAddress.detail }}
                                    </div>
                                </div>
                            </template>
                        </van-cell>
                        <van-cell
                            class="note-cell"
                            v-if="state.remark"
                            :style="{
                                borderRadius: state.userReceiveAddress.phone
                                    ? ' 0 0 10px 10px'
                                    : '10px'
                            }"
                            :title="state.remark"
                            icon-prefix="icon"
                            icon="message1"
                            is-link
                            @click="onAddRemark"
                        >
                            <template #icon>
                                <c-icon name="message1" color="#555555" />
                            </template>
                        </van-cell>
                    </div>

                    <div class="add-remark" v-if="!state.remark" @click="onAddRemark">添加备注</div>
                </div>
                <div class="keyborder-box" @click="onKeyborderChange">
                    <div class="key-cell">
                        <div class="key-item" data-value="1">1</div>
                        <div class="key-item" data-value="2">2</div>
                        <div class="key-item" data-value="3">3</div>
                        <div class="key-item" data-value="del" @click.stop="handleDeleteKey()">
                            <img src="~@/assets/images/icon-del.png" class="icon-del" />
                        </div>
                    </div>
                    <div class="key-cell">
                        <div class="key-left">
                            <div class="row-cell">
                                <div class="key-item" data-value="4">4</div>
                                <div class="key-item" data-value="5">5</div>
                                <div class="key-item" data-value="6">6</div>
                            </div>
                            <div class="row-cell">
                                <div class="key-item" data-value="7">7</div>
                                <div class="key-item" data-value="8">8</div>
                                <div class="key-item" data-value="9">9</div>
                            </div>
                            <div class="row-cell">
                                <div class="key-item key-zero" data-value="0">0</div>
                                <div class="key-item" data-value=".">.</div>
                            </div>
                        </div>
                        <div
                            class="key-item key-confirm"
                            data-value="confirm"
                            @click.stop="handleConfirmKey"
                        >
                            付款
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <CreateRemark
            :show="state.showPopup"
            :init-data="state.remark"
            @close="onClickCloseIcon"
            @change="onRemarkConfirm"
        ></CreateRemark>
        <CreateAddress
            :show="showAddressPopup"
            :init-data="addressState"
            @close="onAddressClickCloseIcon"
            @change="onAddressConfirm"
        >
        </CreateAddress>
    </c-page>
</template>

<style scoped lang="less">
@import './index.less';
</style>
